package main

import (
	"GameServer/Common/data"
	"GameServer/Common/module"
	"GameServer/Common/utils"
	"GameServer/Game/active_user"
	"GameServer/Game/activity"
	"GameServer/Game/activity_rank"
	"GameServer/Game/advert"
	"GameServer/Game/christmas"
	"GameServer/Game/dbmodule"
	"GameServer/Game/energy_quick"
	"GameServer/Game/entrust_activ"
	"GameServer/Game/entrust_rank"
	"GameServer/Game/jackpot"
	"GameServer/Game/m"
	"GameServer/Game/mulcombat"
	"GameServer/Game/player"
	"GameServer/Game/plog"
	"GameServer/Game/rank"
	"GameServer/Game/slot_fire"
	"GameServer/Game/slot_steal"
	"GameServer/Game/sp"
	"GameServer/Game/union"
	protocol "GameServer/Protocol"
	"GameServer/Protocol/protocol/sproto"
	"GameServer/ServerWeb/cmd"
	"GameServer/conf"
	"flag"
	"fmt"
	"math/rand"
	"net"
	"os"
	"os/signal"
	"path"
	"runtime"
	"runtime/debug"
	"syscall"
	"time"

	rotatelogs "github.com/lestrrat/go-file-rotatelogs"
	"github.com/rifflock/lfshook"
	log "github.com/sirupsen/logrus"
)

type params struct {
	*flag.FlagSet `json:"-"`
	appConf       string
	jsonConfDir   string
	logDir        string
	logName       string
	debug         bool
	help          bool
	webPort       string
	pprofPort     string
}

func init() {
	runtime.GOMAXPROCS(runtime.NumCPU())
	runtime.SetMutexProfileFraction(1) // 开启对锁调用的跟踪
	runtime.SetBlockProfileRate(1)     // 开启对阻塞操作的跟踪
	debug.SetTraceback("system")
	rand.Seed(time.Now().UnixNano())

}

func main() {

	defer func() {
		if err := recover(); err != nil {
			fmt.Println("stacktrace from panic main: \n" + string(debug.Stack()))
			fmt.Println("err----1111111-->:", err)
		}
	}()

	cmdParams := &params{}
	cmdParams.FlagSet = flag.NewFlagSet("Cmt1 Server Params", flag.ContinueOnError)
	cmdParams.StringVar(&cmdParams.appConf, "app-config", "appconf/app.config", "app.config 配置文件")
	cmdParams.StringVar(&cmdParams.jsonConfDir, "data-dir", "data/json", "游戏配置json配置文件目录")
	cmdParams.StringVar(&cmdParams.logDir, "debug-log-dir", "debug-log", "debug log目录")
	cmdParams.StringVar(&cmdParams.logName, "debug-log-name", "debug-log", "debug log文件名")
	cmdParams.StringVar(&cmdParams.webPort, "web-port", "8879", "web port")
	cmdParams.StringVar(&cmdParams.pprofPort, "PprofPort", "2014", "pprof")
	cmdParams.BoolVar(&cmdParams.debug, "debug", true, "open debug log")
	cmdParams.BoolVar(&cmdParams.help, "h", false, "help")
	log.Info(os.Args)
	err := cmdParams.Parse(os.Args[1:])
	if err != nil {
		os.Exit(0)
	}

	if cmdParams.help {
		cmdParams.Usage()
		return
	}

	err = conf.Conf.Load(cmdParams.appConf)
	if err != nil {
		log.Fatal("config load err:", err)
	}

	err = data.Init(cmdParams.jsonConfDir)
	if err != nil {
		log.Fatal("游戏配置表加载失败:", err)
	}

	if cmdParams.debug {
		log.SetLevel(log.DebugLevel)
	}

	err = ConfigLocalFilesystemLogger(cmdParams.logDir, cmdParams.logName)
	if err != nil {
		log.Fatal(err)
	}

	utils.SetJsonConfDir(cmdParams.jsonConfDir)
	// 设置时区
	log.Info("时区设置", conf.Conf.TimeZone)
	err = utils.SetLocation(conf.Conf.TimeZone)
	if err != nil {
		log.Fatal("时区设置错误:", err)
	}

	// plog.InitPLogDB()

	err = plog.InitPlog("event-log")
	if err != nil {
		log.Fatal(err)
	}

	module.Run(
		dbmodule.MgoDB,
		player.PlayersModule,
		slot_fire.Module,
		slot_steal.Module,
		union.UnionModule,
		rank.RankModule,
		activity.ActivityModule,
		activity_rank.ActivityRankModule,
		mulcombat.Module,
		entrust_activ.Module,
		entrust_rank.Module,
		active_user.Module,
		jackpot.Module,
		advert.Module,
		energy_quick.Module,
		christmas.Module,
	)

	log.Info("start http api ", conf.Conf.HttpPort)
	go cmd.Run(conf.Conf.HttpPort)

	log.Info("start pprof  ", conf.Conf.PprofPort)
	go cmd.RunPProf(conf.Conf.PprofPort)

	log.Info("start tcp listen  ", conf.Conf.TCP.Port)
	ln, err := net.Listen("tcp", ":"+conf.Conf.TCP.Port)
	if err != nil {
		log.Fatal(err)
	}

	protocl := sproto.NewSprotoPtotocol(sp.Protocols)
	f := func() protocol.ClientCallBack {
		return player.NewPlayer()
	}
	server := protocol.NewTcpServer(ln, f, protocl)
	log.Debug("start server listen port:", conf.Conf.TCP.Port)

	go server.Start()

	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt, os.Kill, syscall.SIGINT, syscall.SIGTERM)
	sig := <-c
	fmt.Println("server closing down signal:", sig)
	log.Debugf("server closing down (signal: %v)\n", sig)

	server.Stop()
	m.Cache.SaveAll()

	module.Destroy()

	log.Debug("server stop success\n")
	fmt.Println("server stop success")
}

func ConfigLocalFilesystemLogger(logPath string, logFileName string) (err error) {
	baseLogPaht := path.Join(logPath, logFileName)
	writer, err := rotatelogs.New(
		baseLogPaht+".%Y%m%d%H%M",
		rotatelogs.WithLinkName(baseLogPaht), // 生成软链，指向最新日志文件
	)
	if err != nil {
		log.Errorf("config local file system logger error. %+v", err)
		return
	}
	lfHook := lfshook.NewHook(lfshook.WriterMap{
		log.DebugLevel: writer, // 为不同级别设置不同的输出目的
		log.InfoLevel:  writer,
		log.WarnLevel:  writer,
		log.ErrorLevel: writer,
		log.FatalLevel: writer,
		log.PanicLevel: writer,
	}, &log.JSONFormatter{})
	log.AddHook(lfHook)
	return
}
